<template>
    <div v-if="$route.name === 'Vi'" class="vaccine-stock-page">
        <el-card class="page-card">
            <template #header>
                <div class="card-header">
                    <span class="header-title">疫苗基础信息</span>
                    <div class="search-container">
                        <el-input v-model="searchForm.keyword" @blur="handleInputBlur" placeholder="疫苗名称/生产厂家"
                            class="search-input" clearable @keyup.enter="handleSearch" />
                        <div class="button-group">
                            <el-button type="primary" @click="handleSearch" class="search-btn">搜索</el-button>
                            <el-button type="success" @click="handleExport" :loading="exportLoading" class="export-btn">
                                <el-icon>
                                    <Download />
                                </el-icon>
                                导出数据
                            </el-button>
                        </div>
                    </div>
                </div>
            </template>

            <!-- 疫苗信息表格 -->
            <div class="table-container">
                <el-table :data="vaccineList" v-loading="loading" style="width: 100%" stripe border
                    :scroll="{ x: 1200 }">
                    <el-table-column prop="id" label="序号" width="60" align="center" fixed="left" />
                    <el-table-column prop="vaccineName" label="疫苗名称" min-width="120" show-overflow-tooltip />
                    <el-table-column prop="manufacturer" label="生产厂家" min-width="120" show-overflow-tooltip />
                    <el-table-column prop="batchNumber" label="生产批号" width="100" align="center" />
                    <el-table-column prop="specification" label="规格" width="80" align="center" />
                    <el-table-column prop="storageCondition" label="存储条件" width="100" align="center" />
                    <el-table-column prop="validityPeriod" label="有效期(月)" width="90" align="center" />
                    <el-table-column prop="description" label="疫苗描述" min-width="150" show-overflow-tooltip />
                    <el-table-column prop="createTime" label="创建时间" width="120" align="center" />
                    <el-table-column label="操作" width="120" align="center" fixed="right">
                        <template #default="{ row }">
                            <div class="action-buttons">
                                <el-button link type="primary" size="small"
                                    @click="handleViewDetail(row.id)">详情</el-button>
                                <el-button link type="danger" size="small" @click="handleCheckStock(row)">删除</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :total="pagination.total" :hide-on-single-page="true" layout="prev, pager, next"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>
    </div>
    <router-view></router-view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from "vue-router";
const router = useRouter();
import { ElLoading, ElMessageBox, ElMessage } from 'element-plus'
import axios from "axios";
import { Download } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

const loading = ref(false)
const vaccineList = ref([])
const exportLoading = ref(false)

// 搜索表单
const searchForm = reactive({
    keyword: ''
})

// 分页配置
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
})

// 搜索
const handleSearch = () => {
    axios.get("http://127.0.0.1:8081/vaccine/search", {
        headers: {
            'X-Admin-Token': sessionStorage.getItem("token")
        },
        params: {
            page: pagination.currentPage,
            size: pagination.pageSize,
            keyword: searchForm.keyword
        }
    }).then((req) => {
        vaccineList.value = req.data.Data
        pagination.currentPage = req.data.pageNum
        pagination.pageSize = req.data.pageSize
        pagination.total = req.data.total
    })
}

//失去焦点触发
const handleInputBlur = (event) => {
    console.log('输入框失去焦点', event)
    if (searchForm.keyword.trim()) {
        // 失去焦点时如果有内容，自动搜索
        handleSearch()
    } else {
        fetchVaccineList()
    }
}

// 导出疫苗数据
const handleExport = async () => {
    try {
        exportLoading.value = true

        // 确认导出范围
        let exportParams = {}
        let message = '确定要导出全部疫苗数据吗？'

        if (searchForm.keyword.trim()) {
            // 使用自定义对话框让用户选择导出方式
            const exportType = await selectExportType()

            if (!exportType) {
                // 用户取消了选择
                return
            }

            if (exportType === 'vaccineName') {
                exportParams = { vaccineName: searchForm.keyword }
                message = `确定要导出疫苗名称包含"${searchForm.keyword}"的数据吗？`
            } else if (exportType === 'manufacturer') {
                exportParams = { manufacturer: searchForm.keyword }
                message = `确定要导出生产厂家包含"${searchForm.keyword}"的数据吗？`
            }
        }

        await ElMessageBox.confirm(message, '导出确认', {
            confirmButtonText: '确定导出',
            cancelButtonText: '取消',
            type: 'warning'
        })

        // 调用导出API
        const response = await axios.get("http://127.0.0.1:8081/vaccine/export/vaccine", {
            headers: {
                'X-Admin-Token': sessionStorage.getItem("token")
            },
            params: exportParams,
            responseType: 'blob'
        })

        // 创建下载链接
        const blob = new Blob([response.data])
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url

        // 设置文件名
        const filename = getFilenameFromResponse(response) || `vaccine_export_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`
        link.download = filename

        // 触发下载
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)

        ElMessage.success('导出成功')

    } catch (error) {
        if (error !== 'cancel') {
            console.error('导出失败:', error)
            ElMessage.error('导出失败，请重试')
        }
    } finally {
        exportLoading.value = false
    }
}

// 选择导出类型
const selectExportType = () => {
    return new Promise((resolve) => {
        ElMessageBox.confirm(
            `请选择按哪个字段导出"${searchForm.keyword}"：`,
            '选择导出字段',
            {
                confirmButtonText: '按疫苗名称导出',
                cancelButtonText: '按生产厂家导出',
                type: 'warning',
                distinguishCancelAndClose: true
            }
        )
            .then(() => {
                resolve('vaccineName')
            })
            .catch((action) => {
                if (action === 'cancel') {
                    resolve('manufacturer')
                } else {
                    resolve(null)
                }
            })
    })
}

// 从响应头获取文件名
const getFilenameFromResponse = (response) => {
    const contentDisposition = response.headers['content-disposition']
    if (contentDisposition) {
        const filenameMatch = contentDisposition.match(/filename="?(.+)"?/i)
        if (filenameMatch && filenameMatch.length > 1) {
            return decodeURIComponent(filenameMatch[1])
        }
    }
    return null
}

// 获取疫苗列表
const fetchVaccineList = async () => {
    const loadingInstance = ElLoading.service({
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    axios.get("http://127.0.0.1:8081/vaccine/list", {
        headers: {
            'X-Admin-Token': sessionStorage.getItem("token")
        },
        params: {
            page: pagination.currentPage,
            size: pagination.pageSize,
        }
    }).then((req) => {
        vaccineList.value = req.data.Data
        pagination.currentPage = req.data.pageNum
        pagination.pageSize = req.data.pageSize
        pagination.total = req.data.total
    }).catch((error) => {
        console.error('请求失败:', error);
        ElMessage.error('请求失败，请检查网络连接');
    })
        .finally(() => {
            loadingInstance.close();
        });
}

// 分页事件
const handleSizeChange = (newSize) => {
    pagination.pageSize = newSize
    fetchVaccineList()
}

const handleCurrentChange = (newPage) => {
    pagination.currentPage = newPage
    fetchVaccineList()
}

// 操作事件
const handleViewDetail = (row) => {
    router.push({
        path: '/Vi/VaccineDetail',
        query: { id: row }
    })
}
const handleCheckStock = (row) => {
    console.log('查看库存:', row)
}

onMounted(() => {
    fetchVaccineList()
})
</script>

<style scoped>
.vaccine-stock-page {
    padding: 16px;
    min-height: 100vh;
    background-color: #f5f7fa;
}

.page-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
}

.header-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    white-space: nowrap;
}

.search-container {
    display: flex;
    align-items: center;
    gap: 12px;
    flex: 1;
    justify-content: flex-end;
}

.search-input {
    width: 280px;
    /* 减小搜索框宽度 */
}

.button-group {
    display: flex;
    gap: 8px;
    /* 减小按钮间距 */
}

.search-btn,
.export-btn {
    white-space: nowrap;
    height: 32px;
    /* 统一按钮高度 */
    padding: 0 12px;
    /* 减小按钮内边距 */
}

.table-container {
    width: 100%;
    overflow-x: auto;
}

.action-buttons {
    display: flex;
    gap: 8px;
    /* 操作按钮并排显示 */
    justify-content: center;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}

/* 平板设备 */
@media (max-width: 1024px) {
    .vaccine-stock-page {
        padding: 12px;
    }

    .card-header {
        flex-direction: column;
        align-items: stretch;
        gap: 12px;
    }

    .search-container {
        justify-content: stretch;
    }

    .search-input {
        width: 100%;
        min-width: auto;
    }

    .button-group {
        width: 100%;
    }

    .search-btn,
    .export-btn {
        flex: 1;
    }
}

/* 手机设备 */
@media (max-width: 768px) {
    .vaccine-stock-page {
        padding: 8px;
    }

    .header-title {
        font-size: 16px;
        text-align: center;
    }

    .card-header {
        gap: 12px;
    }

    .search-container {
        gap: 8px;
    }

    .button-group {
        flex-direction: column;
        gap: 8px;
    }

    :deep(.el-table) {
        font-size: 12px;
    }

    :deep(.el-table th),
    :deep(.el-table td) {
        padding: 4px 8px;
    }
}

/* 小屏手机 */
@media (max-width: 480px) {
    .vaccine-stock-page {
        padding: 4px;
    }

    .header-title {
        font-size: 14px;
    }

    :deep(.el-table) {
        font-size: 11px;
    }

    :deep(.el-table th),
    :deep(.el-table td) {
        padding: 2px 4px;
    }
}

/* 表格滚动条样式 */
:deep(.el-table__body-wrapper) {
    scrollbar-width: thin;
    scrollbar-color: #c0c4cc #f5f7fa;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar {
    height: 8px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
    background: #f5f7fa;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 4px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover {
    background: #909399;
}
</style>